package com.example.firstapp;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.content.DialogInterface;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;

import util.MyDatabaseHelper;

import com.example.firstapp.entity.Sign;
import service.SignService;

public class SignActivity extends AppCompatActivity {
    private TextView et_name, et_photoNumber, et_password, et_enPassword;
    private Button bt_sign, bt_break;
    private SQLiteDatabase db;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sign);

        //链接数据库
        MyDatabaseHelper helper = new MyDatabaseHelper(this, "FistApp.db", null, 1);

        //获取数据库对象
        db = helper.getWritableDatabase();

        //绑定组件
        et_name = findViewById(R.id.editText_name);
        et_photoNumber = findViewById(R.id.editText_Phone);
        et_password = findViewById(R.id.editText_password);
        et_enPassword = findViewById(R.id.editText_enPassword);
        bt_sign = findViewById(R.id.bt_sign);
        bt_break = findViewById(R.id.bt_break);

        /*
         * 监听组件
         * 用匿名监听组件
         */
        //注册按钮监听
        bt_sign.setOnClickListener(view -> {
            Sign sign = new Sign(et_name.getText().toString(),
                    et_photoNumber.getText().toString(),
                    et_password.getText().toString(),
                    et_enPassword.getText().toString());
            SignService.sign(db, sign);
            dialog(sign.isState(), sign.getMessage());
        });

        //返回按钮监听
        bt_break.setOnClickListener(view -> {
            SignActivity.this.finish();
        });

    }

    public void dialog(Boolean state, String message) {
        AlertDialog dialog;
        dialog = new AlertDialog.Builder(this).setTitle("提示")
                .setMessage(message)
                .setIcon(R.mipmap.ic_ke)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        if (state) {
                            SignActivity.this.finish();
                        }
                    }
                })
                .create();
        dialog.show();
    }
}